package org.example.system.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.example.system.entity.CourseEntity;
import org.example.system.service.CourseService;
import org.example.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 课程控制层
 */
@RestController
@RequestMapping("/admin/course")
@Slf4j
public class CourseController {

    @Autowired
    private CourseService courseService;

    /**
     * 按条件分页查询
     * @param course
     * @return
     */
    @GetMapping("/list")
    public R list(CourseEntity course) {
        log.info("------------CourseController | list | input : {} ", JSON.toJSONString(course));
        IPage<CourseEntity> page = courseService.selectPage(course);
        log.info("------------CourseController | list | return : {} ", JSON.toJSONString(page));
        return R.ok(page);
    }

    /**
     * 添加课程
     * @param course
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody CourseEntity course) {
        log.info("---------CourseController | add | input : {}", JSON.toJSON(course));
        int row = courseService.add(course);
        if (row <= 0) {
            return R.fail("添加失败");
        }
        return R.ok("添加成功");
    }

    /**
     * 修改
     * @param course
     * @return
     */
    @PutMapping("/update")
    public R update(@RequestBody CourseEntity course) {
        log.info("---------CourseController | update | input : {}", JSON.toJSON(course));
        if (null == course.getId() || course.getId() <= 0) {
            return R.fail("参数错误:ID未传入");
        }
        int row = courseService.update(course);
        if (row <= 0) {
            return R.fail("修改失败");
        }
        return R.ok("修改成功");
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @DeleteMapping("/delete/{ids}")
    public R delete(@PathVariable("ids") Long[] ids) {
        log.info("---------CourseController | delete | input : {}", JSON.toJSON(ids));
        int row = courseService.deleteBatch(ids);
        if (row <= 0) {
            return R.fail("删除失败");
        }
        return R.ok("删除成功");
    }

    /**
     * 根据id查询课程数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getInfo(@PathVariable("id") Long id) {
        log.info("---------CourseController | getInfo | input : {}", JSON.toJSON(id));
        return R.ok(courseService.getOne(id));
    }
}
